/*package com.smarttest.portal.service.timertask;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.ThreadPoolExecutor.CallerRunsPolicy;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;

import javax.annotation.Resource;

import org.apache.commons.lang.StringUtils;
import org.joda.time.DateTime;
import org.joda.time.format.DateTimeFormat;
import org.joda.time.format.DateTimeFormatter;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import com.alibaba.fastjson.JSONObject;
import com.chinaway.gps.model.GpsCard;
import com.chinaway.gps.model.Location;
import com.smarttest.portal.refresh.gps.dao.LctTraceDao;
import com.smarttest.portal.refresh.gps.manager.GpsCardManager;
import com.smarttest.portal.refresh.gpsevent.dao.StopEventDao;
import com.smarttest.portal.refresh.gpsevent.hanlder.impl.StopMonitorHandler;

@Service
public class StopRefreshMonitor {
	private final ConcurrentHashMap<Integer, AtomicInteger> metrics = new ConcurrentHashMap<Integer, AtomicInteger>();
	private final Logger logger = LoggerFactory.getLogger(getClass());
	private Date startTime;
	private Date endTime;
	private int batchSize = 40;
	// public static boolean REFRESH_RANGE = true;
	public static boolean REFRESH_STOP = true;
	// public static boolean REFRESH_SPEED = false;
	@Value("${orgCodes}")
	private String orgCodes;

	private ThreadPoolExecutor threadPool;

	public static int stop_Bef = 1;
	public static int stop_Af = 2;

	@Resource
	private List<StopMonitorHandler> handlers;
	@Resource
	private GpsCardManager cardManager;
	@Resource
	private LctTraceDao lctTraceDao;
	@Resource
	private StopEventDao stopEventDao;

	public JSONObject getAllStopEvent() {
		JSONObject json = new JSONObject();
		initDate();
		initThreadPool();
		ConcurrentHashMap<Integer, AtomicInteger> map = process();
		stop();
		int StopBefore = map.get(stop_Bef).intValue();
		int StopAfter = map.get(stop_Af).intValue();
		json.put("StopBefore", StopBefore);
		json.put("StopAfter", StopAfter);

		return json;
	}

	private void initThreadPool() {
		threadPool = new ThreadPoolExecutor(50, 50, 300L, TimeUnit.SECONDS,
				new LinkedBlockingQueue<Runnable>(20));
		threadPool.setRejectedExecutionHandler(new CallerRunsPolicy());

	}

	private void initDate() {
		DateTime dt = new DateTime();
		DateTime yesterday = dt.minusDays(1);
		String strStart = yesterday.toString("yyyy-MM-dd 00:00:00");
		String strEnd = yesterday.toString("yyyy-MM-dd 23:59:59");
		DateTimeFormatter format = DateTimeFormat
				.forPattern("yyyy-MM-dd HH:mm:ss");
		DateTime dateStart = DateTime.parse(strStart, format);
		DateTime dateEnd = DateTime.parse(strEnd, format);
		startTime = dateStart.toDate();
		endTime = dateEnd.toDate();
	}

	private ConcurrentHashMap<Integer, AtomicInteger> process() {
		long start = System.currentTimeMillis();
		logger.info("停留点开始初始化......");
		logger.info("停留点刷新参数：本次刷新事件:STOP:{},刷新区域:START:{},END:{}", REFRESH_STOP,
				startTime, endTime);

		String[] orgcodeArr = StringUtils.split(orgCodes, ",");
		Map<String, GpsCard> cardMap = new HashMap<String, GpsCard>();
		for (String orgcode : orgcodeArr) {
			Map<String, GpsCard> map = cardManager.findByOrgcode(orgcode);
			cardMap.putAll(map);
			logger.info("开始初始化GPSCARD,通过ORGCODE:{}", orgcode);
		}
		
		 * if (StringUtils.isNotBlank(imei)) {
		 * logger.info("开始初始化GPSCARD,通过IMEI:{}", imei); cardMap =
		 * cardManager.findByImeis(imei); } else {
		 * logger.info("开始初始化GPSCARD,通过ORGCODE:{}", orgcode); cardMap =
		 * cardManager.findByOrgcode(orgcode); }
		 
		logger.info("初始化GPSCARD完成.需要刷新的设备数 ：{}", cardMap.size());
		metrics.put(stop_Bef, new AtomicInteger(0));
		metrics.put(stop_Af, new AtomicInteger(0));
		if (cardMap.size() == 0) {
			logger.info("没有需要刷新的设备 scope");
			System.exit(0);
		}

		logger.info("===============================");

		final LinkedBlockingQueue<GpsCard> queue = new LinkedBlockingQueue<GpsCard>();
		queue.addAll(cardMap.values());
		final CountDownLatch cd = new CountDownLatch(batchSize);

		for (int i = 0; i < batchSize; i++) {
			threadPool.execute(new Runnable() {
				@Override
				public void run() {
					try {
						while (true) {
							GpsCard card = queue.poll(10, TimeUnit.SECONDS);
							if (card == null) {
								logger.info("线程10秒内未能获取到数据;自行消亡");
								return;
							}
							//
							long start = System.currentTimeMillis();
							logger.info("开始刷新设备：{}", card.getGpsid());
							HashMap<Integer, Integer> countMap = scanDevices(card);
							int countBefore = metrics.get(stop_Bef).addAndGet(
									countMap.get(stop_Bef));
							int countAfter = metrics.get(stop_Af).addAndGet(
									countMap.get(stop_Af));

							metrics.put(stop_Bef,
									new AtomicInteger(countBefore));
							metrics.put(stop_Af, new AtomicInteger(countAfter));

							logger.info("刷新完成设备：{},耗时:{}", card.getGpsid(),
									System.currentTimeMillis() - start);
						}
					} catch (InterruptedException e) {
						e.printStackTrace();
					} finally {
						cd.countDown();
					}
				}
			});
		}

		try {
			cd.await();
			long end = System.currentTimeMillis();
			logger.info("停留点刷新完成===耗时："+(end-start));
			return metrics;
			// System.exit(1);
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
		return metrics;
	}

	private HashMap<Integer, Integer> scanDevices(GpsCard card) {
//		card.setGpsid("107015090021873");
		long start = System.currentTimeMillis();
		String imei = card.getGpsid();
		Date from = startTime;

		HashMap<Integer, Integer> countMap = new HashMap<Integer, Integer>();
		countMap.put(stop_Af, 0);
		int before = stopEventDao.countEvent(imei, startTime, endTime);
//		List<StopEvent> events = stopEventDao.getEvents(imei, startTime, endTime);
		logger.info("查询到设备：{} ，停留点事件：{}条",imei,before);
		countMap.put(stop_Bef, before);

//		while (from.getTime() < endTime.getTime()) {
		List<Location> lcts = new ArrayList<Location>();
		try {
			lcts = lctTraceDao.findByList(card.getGpsid(), from, endTime);
			if (lcts == null || lcts.size() == 0) {
				logger.info("该时间段无定位数据 imei={}", imei);
				return countMap;
//				 break;
			}
		} catch (Exception e) {
			logger.info("获取定位数据失败 imei={}", imei, e);
			return countMap;
//			 break;
		}

		 for (StopMonitorHandler handler : handlers) {
			 try {
			 HashMap<Integer, Integer> map = handler.refreshCount(card, lcts,
			 from, endTime);
			 int count = map.get(stop_Af)+countMap.get(stop_Af);
			 countMap.put(stop_Af, count);
			 } catch (Exception e) {
			 logger.info("刷新事件失败 imei={}, class={}", imei,
			 handler.getClass());
			 }
		 }

		// 逐步向endTime靠近进行刷新
//		 from = lcts.get(lcts.size() - 1).getTime();
//		 if (lcts.size() < 1000) {
//		 //如果轨迹点小于1000个就不再执行
//		 break;
//		 }
//		 }
		 long time = System.currentTimeMillis() - start;
		 logger.info("刷新devices={}, 用时 {} ms", card.getGpsid(), time);
		 return countMap;
	}

	private void stop() {
		threadPool.shutdown();
	}
}
*/